import React, { useEffect, useState } from "react";
import {
  Form,
  Input,
  Button,
  Row,
  Col,
  Switch,
  message,
  Spin,
  Tooltip,
  Icon
} from "antd";
import { connect } from "dva";
import styles from "./AddTemplate.less";
import EditTable from "./components/editTable";
import {
  // saveMessageTemplate,
  getTemplateDetail,
  commitMessageTemplate,
  updateMessageTemplate
  // getSmsSign
} from "../../services/messageTemplateApi";
import { getQueryVariable } from "../../../../utils/utils";

const { TextArea } = Input;

function AddTemplate(props) {
  const {
    form,
    history,
    // location: { search },
    userInfo,
    collapsed
  } = props;
  // const searchParams = new URLSearchParams(search.substring(1));
  // const templateId = searchParams.get("templateId");
  const templateId = getQueryVariable("templateId");
  // const id = searchParams.get("id");
  const {
    getFieldDecorator,
    getFieldValue,
    setFieldsValue,
    // getFieldsValue,
    validateFields
  } = form;
  const [listOfParams, setListOfParams] = useState([]);
  const [loading, setloading] = useState(false);
  const [spinning, setSpinning] = useState(false);

  // 编辑时数据回显
  useEffect(() => {
    if (templateId) {
      setSpinning(true);
      getTemplateDetail({ templateId }).then(res => {
        if (res.success) {
          /* eslint-disable */
          const data = res.datas;
          // const paramMap = data.paramList;
          setFieldsValue({
            ...data,
            isEnabled: data.isEnabled === "Y"
          });
          // let paramsArr = [];
          // for (const key in paramMap) {
          //   if (Object.hasOwnProperty.call(paramMap, key)) {
          //     paramsArr.push({ name: key, desc: paramMap[key] });
          //   }
          // }
          setListOfParams(
            (data.paramList &&
              data.paramList.map(l => ({
                isDeleted: l.isDeleted,
                id: l.id,
                paramName: l.paramName,
                paramDescription: l.paramDescription
              }))) ||
              []
          );
        }
        setSpinning(false);
      });
    }
  }, [templateId]);
  useEffect(() => {
    setFieldsValue({});
  }, []);

  const handleSubmit = () => {
    validateFields().then((values, errs) => {
      if (errs) return;
      setloading(true);
      if (templateId) {
        const params = {
          ...values,
          templateId,
          isEnabled: values.isEnabled ? "Y" : "N",
          tenantCode: "test",
          creator: userInfo.userName,
          modifier: userInfo.userName,
          paramList: listOfParams
        };
        updateMessageTemplate(params).then(res => {
          if (res.success) {
            message.success("操作成功");
            window.history.go(-1);
          } else {
            message.error(res.errMsg);
          }
          setloading(false);
        });
      } else {
        const params = {
          ...values,
          isEnabled: values.isEnabled ? "Y" : "N",
          tenantCode: "test",
          creator: userInfo.userName,
          modifier: userInfo.userName,
          paramList: listOfParams
        };
        commitMessageTemplate(params).then(res => {
          if (res.success) {
            message.success("操作成功");
            window.history.go(-1);
          } else {
            message.error(res.errMsg);
          }
          setloading(false);
        });
      }
    });
  };

  // 同步参数
  const onTrans = () => {
    let arr = [];
    if (getFieldValue("templateContent")) {
      // const regx = new RegExp('(?<=\${).+?(?=})', 'g')
      // const temp = getFieldValue("templateContent").match(/(?<=\${).+?(?=})/g);
      const temp = getFieldValue("templateContent").match(/(\${).+?(})/g) || [];
      const newTemp = temp.map(t => t.replace(/(\${)|}/g, ""));
      if (newTemp) {
        arr = new Set(newTemp);
      }
      // 参数重复时候，提示用户重新操作
      if (newTemp.length !== arr.size) {
        message.error("变量重复，请修改后同步");
        return;
      }
    }
    let tempArr = [];
    arr.forEach(name => {
      // 正向同步，如果参数列表有name值，带到新表格，没有的话直接新增
      if (listOfParams.some(t => t.paramName === name)) {
        tempArr = tempArr.concat([
          {
            paramName: name,
            paramDescription: listOfParams.find(l => l.paramName === name)
              .paramDescription
          }
        ]);
      } else {
        tempArr = tempArr.concat([
          {
            paramName: name,
            paramDescription: ""
          }
        ]);
      }
    });
    setListOfParams(tempArr);
  };

  // 删除参数，反馈更新模板
  const listDel = name => {
    const tempArr = listOfParams
      .map(l => {
        if (l.paramName === name) {
          if (l.id) {
            return { ...l, isDeleted: "Y" };
          }
          return undefined;
        }
        return l;
      })
      .filter(Boolean);
    setListOfParams(tempArr);
    // 更新模板，删除对应的参数
    const tmpContent = getFieldValue("templateContent");
    setFieldsValue({
      templateContent: tmpContent.replace("${" + name + "}", "")
    });
  };

  // 编辑参数，反馈更新模板
  const listUpdate = (row, paramName) => {
    // 如果编辑时，模板数据已经删掉paramName，则提示同步后在处理
    // const regx = new RegExp('(?<=\${).+?(?=})', 'g')
    // const temp = getFieldValue("templateContent").match(/(?<=\${).+?(?=})/g);
    const temp = getFieldValue("templateContent").match(/(\${).+?(})/g) || [];
    const newTemp = temp.map(t => t.replace(/(\${)|}/g, ""));
    if (newTemp.indexOf(paramName) === -1) {
      message.error("当前模板不存在此变量，请同步后再操作");
      return;
    }
    // 编辑的新变量名如果和原列表重复，禁止操作
    if (
      row.paramName !== paramName &&
      listOfParams.find(l => l.paramName === row.paramName)
    ) {
      message.error("当前模板已存在此变量名，请修改后重试");
      return;
    }
    // 编辑表格数据
    const newData = [...listOfParams];
    const index = newData.findIndex(item => paramName === item.paramName);
    if (index > -1) {
      const item = newData[index];
      newData.splice(index, 1, {
        ...item,
        ...row
      });
      setListOfParams(newData);
    } else {
      newData.push(row);
      setListOfParams(newData);
    }
    // 更新模板变量
    // 更新模板，删除对应的参数
    const tmpContent = getFieldValue("templateContent");
    setFieldsValue({
      templateContent: tmpContent.replace(
        "${" + paramName + "}",
        "${" + row.paramName + "}"
      )
    });
    return true;
  };

  const formItemLayout = {
    labelCol: {
      xs: { span: 24 },
      sm: { span: 8 }
    },
    wrapperCol: {
      xs: { span: 24 },
      sm: { span: 16 }
    }
  };

  return (
    <div className={styles.root}>
      <Spin spinning={spinning}>
        <Form {...formItemLayout} style={{ width: 800 }}>
          <Row>
            <Col span={12}>
              <Form.Item label="消息模版编码">
                {getFieldDecorator("templateCode", {
                  rules: [
                    { required: true, message: "请输入消息模版编码" },
                    {
                      pattern: /^[a-zA-Z0-9]([a-zA-Z0-9]|-|_){0,29}$/,
                      message:
                        "请输入30位以内英文+数字+常用字符（下划线、短横线），英文或数字开头"
                    }
                  ]
                })(<Input placeholder="请输入消息模版编码" />)}
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item label="消息模版名称">
                {getFieldDecorator("templateName", {
                  rules: [
                    { required: true, message: "请输入消息模版名称" },
                    {
                      pattern: /^([a-zA-Z0-9]|[\u4E00-\u9FA3])([a-zA-Z0-9]|[\u4E00-\u9FA3]|-|_){0,29}$/,
                      message:
                        "请输入30位以内中英文+数字+常用字符（下划线、短横线），中英文或数字开头"
                    }
                  ]
                })(<Input placeholder="请输入消息模版名称" />)}
              </Form.Item>
            </Col>
          </Row>
          <Row>
            <Col span={12}>
              <Form.Item label="消息模版标题">
                {getFieldDecorator("templateTitle", {
                  rules: [
                    { required: true, message: "请输入消息模版标题" },
                    {
                      pattern: /^([a-zA-Z0-9]|[\u4E00-\u9FA3])([a-zA-Z0-9]|[\u4E00-\u9FA3]|-|_){0,59}$/,
                      message:
                        "请输入60位以内中英文+数字+常用字符（下划线、短横线），中英文或数字开头"
                    }
                  ]
                })(<Input placeholder="请输入消息模版标题" />)}
              </Form.Item>
            </Col>
          </Row>
          <Row>
            <Col span={12}>
              <Form.Item label="启用">
                {getFieldDecorator("isEnabled", { valuePropName: "checked" })(
                  <Switch checkedChildren="开" unCheckedChildren="关" />
                )}
              </Form.Item>
            </Col>
          </Row>
          <Row>
            <Col span={24}>
              <Form.Item
                labelCol={{ span: 4 }}
                wrapperCol={{ span: 20 }}
                label={
                  <span>
                    消息模版内容&nbsp;&nbsp;
                    <Tooltip title="变量用${Variable}">
                      <Icon type="exclamation-circle" />
                    </Tooltip>
                  </span>
                }
              >
                {getFieldDecorator("templateContent", {
                  rules: [
                    { required: true, message: "请输入消息模版内容" },
                    {
                      max: 200,
                      message: "请输入200位以内字符"
                    }
                  ]
                })(<TextArea placeholder="请输入消息模版内容" rows={4} />)}
              </Form.Item>
            </Col>
          </Row>
          <Row>
            <Col span={24}>
              <Form.Item
                labelCol={{ span: 4 }}
                wrapperCol={{ span: 20 }}
                label="备注"
              >
                {getFieldDecorator("description", {
                  rules: [
                    {
                      max: 300,
                      message: "请输入300位以内字符"
                    }
                  ]
                })(<TextArea placeholder="请输入备注" rows={4} />)}
              </Form.Item>
            </Col>
          </Row>
          <Row>
            <Col span={12}>
              <Form.Item label="参数管理">
                <Button type="primary" onClick={onTrans}>
                  同步
                </Button>
              </Form.Item>
            </Col>
          </Row>
          {/* <Table columns={columns} dataSource={listOfParams} /> */}
          <Row>
            <Col span={1}></Col>
            <Col span={23}>
              <EditTable
                listOfParams={listOfParams}
                setListOfParams={setListOfParams}
                listUpdate={listUpdate}
                listDel={listDel}
              />
            </Col>
          </Row>
        </Form>
        <div style={{ height: 80 }} />
        <div
          className={styles.footer}
          style={{
            // width: '100%',
            left: collapsed ? 64 : 200
          }}
        >
          <Button
            onClick={() => {
              history.push("/messageCenter/templateManager");
            }}
            style={{ marginRight: 10 }}
          >
            取消
          </Button>
          <Button
            loading={loading}
            type="primary"
            htmlType="submit"
            onClick={handleSubmit}
          >
            保存
          </Button>
        </div>
      </Spin>
    </div>
  );
}

export default Form.create()(
  connect(({ user: { userInfo, collapsed } }) => ({
    userInfo,
    collapsed
  }))(AddTemplate)
);
